package com.mamesoft.medicipazienti.servlet;

import com.mamesoft.medicipazienti.tools.JDBC;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class LoginServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static Logger log = Logger.getLogger(LoginServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PropertyConfigurator.configure(LoginServlet.class.getClassLoader().getResource("com/mamesoft/medicipazienti/tools/log4j.properties"));

        Connection connect = null;
        PrintWriter out = null;
        boolean isCookieEnable = true;
        try {
            HttpSession session = request.getSession();
            connect = JDBC.connect();
            PropertyConfigurator.configure(LoginServlet.class.getClassLoader().getResource("com/mamesoft/medicipazienti/tools/log4j.properties"));
            response.setContentType("text/html;charset=UTF-8");
            DateFormat d = DateFormat.getDateInstance();

            String nome = null, cognome = null;
            String password = request.getParameter("password");
            String role = request.getParameter("role");
            if (request.getParameter("user") != null) {
                String[] username = request.getParameter("user").split("\\.");

                if (username.length == 2) {
                    nome = username[0];
                    cognome = username[1];
                }
            }

            ResultSet set = null;
            boolean isValidRole = false, userOk = false, registred = true, isDBDown = true;
            String dbNome = null, dbCognome = null, dbPassword, dbData = null, dbFoto = null;
            int dbID = -1;

            if (role == null) {
                role = "";
            }

            if (connect != null) {
                isDBDown = false;
                if ((role.equals("Medico")) || (role.equals("Paziente"))) {
                    isValidRole = true;
                    synchronized (connect) {
                        String query;
                        if ((role.equals("Paziente"))) {
                            query = "SELECT ID,Nome,Cognome,Data,Foto,Password FROM " + request.getParameter("role").toLowerCase()
                                    + " WHERE Nome = \"" + nome + "\" AND Cognome = \"" + cognome + "\"";
                        } else {
                            query = "SELECT ID,Nome,Cognome,Password FROM " + request.getParameter("role").toLowerCase()
                                    + " WHERE Nome = \"" + nome + "\" AND Cognome = \"" + cognome + "\"";

                        }
                        set = JDBC.executeQuery(query, connect);

                        if (set.next()) {
                            dbID = set.getInt("ID");
                            dbNome = set.getString("Nome");
                            dbCognome = set.getString("Cognome");
                            dbNome = dbNome.substring(0, 1).toUpperCase() + dbNome.substring(1).toLowerCase();
                            dbCognome = dbCognome.substring(0, 1).toUpperCase() + dbCognome.substring(1).toLowerCase();
                            dbPassword = set.getString("Password");
                            if (role.equals("Paziente")) {
                                dbData = d.format(set.getTimestamp("Data"));
                                dbFoto = set.getString("Foto");
                            }
                            if (dbPassword != null) {
                                userOk = (dbPassword.equals(password));
                            }
                        }
                    }
                }
            }

            //Se l'user è quello giusto gli do i cookie altrimenti ciccia

            if (userOk) {

                Cookie[] cookies = request.getCookies();
                if (cookies == null) {
                    isCookieEnable = false;
                }
                int cookieIndex = -1;
                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName().equals("login_" + dbID + role)) {
                        cookieIndex = i;
                    }
                }
                if (cookieIndex > 0) {
                    String temp = cookies[cookieIndex].getValue();
                    String s = temp.substring(8, 10) + "-" + temp.substring(5, 7) + "-" + temp.substring(0, 4)
                            + " " + temp.substring(11, 20);
                    session.setAttribute("last_login", "Data ultimo login: " + s);
                } else {
                    session.setAttribute("last_login", "Sembra la prima volta che fai il login");
                }
                Timestamp t = new Timestamp(System.currentTimeMillis());
                Cookie c = new Cookie("login_" + dbID + role, t.toString());
                c.setMaxAge(Integer.MAX_VALUE);
                response.addCookie(c);
                session.setAttribute("id", dbID);
                session.setAttribute("role", role);
                session.setAttribute("nome", dbNome);
                session.setAttribute("cognome", dbCognome);
                if (role.equals("Paziente")) {
                    session.setAttribute("data", dbData);
                    session.setAttribute("foto", dbFoto);
                }

            }
            out = response.getWriter();


            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("    <head>");
            out.println("        <title>Vaccino Manger</title>");
            out.println("        <link rel=\"stylesheet\" type=\"text/css\" href=\"/MediciPazienti/variant-stream.css\" title=\"Variant Stream\" media=\"screen,projection\" />");
            out.println("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">       ");



            if (userOk) {
                response.sendRedirect("/MediciPazienti/" + role.toLowerCase() + "/welcome");
            }
            out.println("    </head>");
            out.println("    <body>");
            out.println("        <div id =\"wrap\">");
            out.println("            <div id=\"header\">");
            out.println("                <div id =\"topmenu\">");
            out.println("                    <p>");
            out.println("                        <a href=\"registrati.html\">Registrati</a>");
            out.println("                    </p>");
            out.println("                </div>");
            out.println("                <div id=\"title\">");
            out.println("                    <h1>Vaccino Manager</h1><br/>");
            out.println("                    <h2 class =\"slogan\">I tuoi vaccini contano</h2>");
            out.println("                </div>");
            out.println("            </div>");
            out.println("            <div id=\"sidebar\">");
            out.println("                <form action=\"/MediciPazienti/login_servlet\" method=\"POST\">");
            out.println("                    <p class =\"sidemenu\">");
            out.println("                        Username: <br/>");
            out.println("                        <input type=\"text\" name=\"user\" value=\"\" />");
            out.println("                    </p>");
            out.println("                    <p class =\"sidemenu\">");
            out.println("                        Password: <br/>");
            out.println("                        <input type=\"password\" name=\"password\" value=\"\" />");
            out.println("                    </p>");
            out.println("                    <p class =\"sidemenu\">");
            out.println("                        <select name=\"role\">");
            out.println("                            <option>-->Scegli un ruolo</option>");
            out.println("                            <option>Medico</option>");
            out.println("                            <option>Paziente</option>");
            out.println("                        </select>");
            out.println("                    </p>");
            out.println("                    <p>");
            out.println("                        <input type=\"reset\" value=\"Cancella\" />");
            out.println("                        <input type=\"submit\" value=\"Login\" />");
            out.println("                    </p>");
            out.println("                </form>");
            out.println("            </div>");
            out.println("            <div id =\"content\">");
            out.println("                <div id=\"feature\">");
            out.println("                    <p>Sample Text</p>");
            out.println("                </div>");
            out.println("                <div class=\"post\">");

            if (!isDBDown) {
                if (!userOk) {
                    out.println("                   <p>Hai inserito un nome utente o una password non validi. Per favore inserisci i dettagli corretti e riprova.</p>");
                    out.println("                   <p>Se non ti sei ancora registrato clicca <a href=\"registrati.html\">qui</a>.</p>");
                }
                if (!isValidRole) {
                    out.println("<p>Hai selezionato il ruolo?</p>");
                }
            } else {
                out.println("                   <p>Il database è momentaneamente fuori uso, si prega di riprovare più tardi.</p>");
            }
            out.println("                </div>");
            out.println("            </div>");
            out.println("            <div id=\"footer\">");
            out.println("                <p class=\"centered\">Copyright &copy; 2011 <a href=\"/MediciPazienti/index.html\">Mamesoft</a>");
            out.println("                    Progetto Programmazione per il web A.A.2011/2012</p>");
            out.println("            </div>");
            out.println("        </div>");
            out.println("    </body>");
            out.println("</html>");

        } catch (Exception ex) {
            request.getSession().invalidate();
            if (isCookieEnable) {
                if (ex instanceof SQLException | (ex instanceof ClassNotFoundException & ex instanceof InstantiationException & ex instanceof IllegalAccessException)) {
                    log.error("Database Error: " + ex.toString());
                    response.sendRedirect("/MediciPazienti/database_error.html");
                } else {
                    log.error("Generic error: " + ex.toString());
                    response.sendRedirect("/MediciPazienti/general_error.html");
                }
            } else {
                log.error("Cookie rejected");
                response.sendRedirect("/MediciPazienti/no_cookie.html");

            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (connect != null) {
                try {
                    connect.close();
                } catch (Exception ex) {
                    request.getSession().invalidate();
                    log.error("Database Error: " + ex.toString());
                    response.sendRedirect("/MediciPazienti/database_error.html");
                }
            }
        }
    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
